package ran.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import ran.entity.TableDataInfo;
import ran.friend.domain.question.dto.QuestionQueryDTO;
import ran.friend.domain.question.entity.Question;
import ran.friend.domain.question.es.QuestionES;
import ran.friend.domain.question.vo.QuestionDetailVO;
import ran.friend.domain.question.vo.QuestionVO;
import ran.friend.elsticsearch.QuestionRepository;
import ran.friend.manager.QuestionRedisCacheManager;
import ran.friend.mapper.question.QuestionMapper;
import ran.friend.service.question.IQuestionService;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-11-17
 * Time: 13:26
 */
@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRedisCacheManager questionRedisCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        // 先去ES中查询, 没有的话再去MySQL查询,并刷新缓存
        long count = questionRepository.count();
        if (count <= 0) {
            // 先同步缓存
            refreshCache();
        }
        // 刷新完缓存后, 这里是有数据的
        String keyword = questionQueryDTO.getKeyword();
        Integer difficulty = questionQueryDTO.getDifficulty();
        // 排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        // 分页规则
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(),sort);
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            // 参数都为空
            questionESPage = questionRepository.findAll(pageable);
        }else if (StrUtil.isEmpty(keyword)) {
            // difficulty 参数不为null
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        } else if (difficulty == null) {
            // keyword 即 按题目或内容查询 参数不为空
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        }else {
            // 都不为空
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        // 判断当前刷新缓存后的ES中获取的数据是否仍为空
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        // 将集合数据转化为VO
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOS = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOS,total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        // 先去ES当中查询
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        // ES为空, 去MySQL数据库中查询
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        // 刷新ES缓存
        refreshCache();

        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionRedisCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionRedisCacheManager.refreshCache();
        }
        // 从Redis中查询
        return questionRedisCacheManager.preQuestion(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionRedisCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionRedisCacheManager.refreshCache();
        }
        // 从Redis中查询
        return questionRedisCacheManager.nextQuestion(questionId).toString();
    }

    private void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>().orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }
}
